
# 抽取代码
"""
把某一部分代码能够实现特定功能的抽取出来（一个功能的代码出现2次，一个功能的代码太长了）
# 1.将代码原封不动的复制到另一个方法中，哪里有问题改哪里，对应的数据如果没有以参数的形式传递
# 2.将复制的代码注释掉，调用抽取的代码进行验证
"""
import json
from urllib.parse import urlencode,parse_qs
from urllib.request import urlopen

from rest_framework import status
from rest_framework.response import Response

from mall import settings


class QQOauthTool(object):
    # def __init__(self,client_id=None,redirect_uri=None):
    #     self.client_id = client_id or settings.QQ_APP_ID
    #     self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URL


    def get_oauth_url(self):
        state = '/'
        base_url = 'https://graph.qq.com/oauth2.0/authorize?'
        # 使用字典同时调用urlencode(参数)方法自动生成url,也就是拼接查询字符串
        # state = request.query_params.get('state')
        # print(state)
        params = {
            'response_type': 'code',
            'client_id': settings.QQ_APP_ID,
            'redirect_uri': settings.QQ_REDIRECT_URL,
            'state':state,
            # 'state': '/',

        }
        # 调用urlencode()拼接查询字符串
        auth_url = base_url + urlencode(params)
        return auth_url

    def get_token_by_code(self,code):
        base_url = 'https://graph.qq.com/oauth2.0/token?'
        # 获取code
        # code = request.query_params.get('code')
        # if code is None:
        #     return Response(status=status.HTTP_400_BAD_REQUEST)
        # 参数字典
        params = {
            'grant_type':'authorization_code',
            'client_id':settings.QQ_APP_ID,
            'client_secret':settings.QQ_APP_KEY,
            'code':code,
            'redirect_uri':settings.QQ_REDIRECT_URL,
        }
        # 拼接查询字符串
        auth_url = base_url + urlencode(params)
        # 自动请求auth_url地址，调用urlopen()方法
        # 返回response响应对象，可以通过read()读取响应体数据（bytes类型）
        response = urlopen(auth_url)
        data = response.read().decode()
        """
        data:打印出来的是查询字符串，需要用parse_qs():将查询字符串转化为字典
        'access_token=93AA8F5FDCC24083E29F023939E213C4'
        '&expires_in=7776000'
        '&refresh_token=7AE5DC6C564589B865AB89EEC48B17E0'
        """
        # print(data)
        dict = parse_qs(data)
        """
        查询字符串转通过parse_qs()方法转化为字典，字典的值为列表，需要从列表中取值
        {'refresh_token': ['7AE5DC6C564589B865AB89EEC48B17E0'],
        'expires_in': ['7776000'],
        'access_token': ['93AA8F5FDCC24083E29F023939E213C4']}
        """
        # print(dict)
        access_tokens = dict.get('access_token')
        if access_tokens:
            access_token = access_tokens[0]
            return access_token
        else:
            return None

    def get_openid_by_token(self,token):
        # 3.用token拼接参数获取openid
        # 拼接url
        base_url = 'https://graph.qq.com/oauth2.0/me?'
        # GET方法
        # 请求参数：access_token	必须	在Step2中获取到的access token。
        params = {
            'access_token': token,
        }
        url = base_url + urlencode(params)
        response = urlopen(url)
        dict = response.read().decode()
        """
        dict的打印结果：
        'callback( {"client_id":"101474184","openid":"8BA7A611347DB6D716A35E6712EFAADE"} );'
        """
        # print(dict)
        try:
            data = json.loads(dict[10:-4])
        except Exception:
            return None
        openid = data.get('openid')
        if openid:
            return openid
        else:
            return None